<template>
  <el-dialog
    v-model="show"
    :title="isUpdate ? '修改属性' : '新增属性'"
    width="600px"
    @close="closeModal"
  >
    <el-form ref="formRef" :model="form" label-width="80px">
      <el-form-item label="计算字段">
        <el-select
          v-model="form.AttrName"
          filterable
          remote
          reserve-keyword
          remote-show-suffix
          :remote-method="remoteMethod"
          :loading="loading"
          placeholder="请输入计算字段"
        >
          <el-option
            v-for="item in attrsData"
            :key="item.value"
            :label="item.AttrName"
            :value="item.AttrName"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="计算类型">
        <el-radio-group v-model="form.computeType">
          <el-radio value="manual">{{ computeTypeMap.manual }}</el-radio>
          <el-radio value="formula">{{ computeTypeMap.formula }}</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <!-- <el-form-item
        label="计算公式"
        prop="AttrValue"
        :rules="computeRules"
        v-if="form.computeType == 'formula'"
      >
        <el-input
          v-model="form.computeFormula"
          type="textarea"
          class="text-[16px]"
          :rows="4"
        />
      </el-form-item> -->
      <el-form-item
        label="计算公式"
        prop="AttrValue"
        :rules="computeRules"
        required
      >
        <!-- <FormulaSelect v-model="formulaStructure" /> -->
        <el-input
          v-model="form.AttrValue"
          class="text-[16px]"
          placeholder="请输入计算公式"
          type="textarea"
          :rows="4"
        />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.AttrRemark" placeholder="请输入备注"></el-input>
      </el-form-item>
      <el-form-item label="排序">
        <el-input
          v-model="form.SortIndex"
          type="number"
          placeholder=""
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="handleConfirm(formRef)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { computed, reactive, toRef, toRefs, watch } from "vue";
import { errMsg } from "@/utils/errorMsg";
import {
  computeCols,
  computeOperatorMap,
  computeTypeMap,
  opeartorSymbolMap,
  orderAttrsMap,
} from "../../../../../utils/map";
import { CircleClose, CirclePlus, Minus } from "@element-plus/icons-vue";
import FormulaSelect from "./FormulaSelect.vue";
import {
  validAttrsName,
  validCalcExpression,
} from "../../../../../utils/validate";
import {
  attrQueryApi,
  attrUpdateApi,
  attrRemoveApi,
} from "@/api/order/attr/index.js";
import useOrderAttrStore from "@/store/modules/orderAttrs";

defineOptions({
  name: "CalcEditModal",
});
const props = defineProps({
  open: {
    type: Boolean,
    required: true,
  },
  isUpdate: {
    type: Boolean,
    required: true,
  },
  data: {
    type: Object,
    required: true,
  },
});
const emits = defineEmits(["closeModal", "reload"]);
const orderAttrStore = useOrderAttrStore();
const state = reactive({
  form: {
    attrChar: "",
    computeType: "",
    computeFormula: ``,
    computeRemark: "",
    formula: "",
  },
  attrsData: [],
  loading: false,
  computeRules: [
    {
      validator: checkFormula,
      trigger: "change",
    },
    {
      required: true,
      message: "请输入计算公式",
      trigger: "blur",
    },
  ],
  formulaStructure: [{ index: 0, operator: "", manual: false, ele: "" }],
  calcEleOptions: computeCols.map((item) => ({
    value: item,
    label: orderAttrsMap[item],
  })),
  formRef: undefined,
});

const {
  form,
  formRef,
  computeRules,
  formulaStructure,
  calcEleOptions,
  attrsData,
  loading,
} = toRefs(state);
watch(
  () => props.open,
  async (val) => {
    show.value = val;
    form.value = Object.assign({}, props.data);
    if (!props.isUpdate) {
      for (let key in form.value) {
        form.value[key] = "";
      }
    }
    const res = await attrQueryApi({
      keyStr: "金额",
      seriesId: orderAttrStore.currentProductSeries.SeriesId,
    });
    attrsData.value = res.Data || [];
  }
);
const show = ref(false);

function closeModal() {
  show.value = false;
  emits("closeModal");
}

function handleConfirm(submitFormRef) {
  submitFormRef.validate((valid, fields) => {
    if (valid) {
      try {
        // 接口请求
        if (props.isUpdate) {
          emits("reload", form.value, true);
        } else {
          form.value.AttrId = 0;
          emits("reload", form.value, false);
        }
        // emits('reload', form.value)
      } catch (error) {
        console.error("未知错误", error);
        // 请求失败处理
        ElMessage.error("修改失败：" + errMsg(error));
      }
      closeModal();
    }
  });
}
function checkFormula(rule, value, callback) {
  if (!value) return;
  let [attrValid, wrongAttr] = validAttrsName(value);
  if (!attrValid) {
    callback(new Error(`未找到属性“${wrongAttr}”`));
  } else if (!value) {
    callback(new Error("计算公式不能为空"));
  } else if (!validCalcExpression(value)) {
    callback(new Error("公式格式有误"));
  }
  callback();
}
async function remoteMethod(str) {
  if (str) {
    loading.value = true;
    const res = await attrQueryApi({
      keyStr: str,
      pageSize: 10000,
      seriesId: orderAttrStore.currentProductSeries.SeriesId,
    });
    attrsData.value = res.Data;
    loading.value = false;
  } else {
    attrsData.value = [];
  }
}
</script>
<style lang="scss">
</style>